﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.GamerServices;

namespace PhysicsSimulator
{
    public partial class LaunchPhysicsPage : PhoneApplicationPage
    {
        const int NUMBER_DOT = 30;
        const int CM_PIXEL = 80;
        const int RATE_METER = 10;
        Vector2 FIST_POSITION = new Vector2(40, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height - 100);
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        UIElementRenderer elementRenderer;


        //Texture2D _background = null;
        CBall _ball;
        CVectorForce _x;
        CVectorForce _y;

        List<WayPoint> _waypoints;

        Dots[] _dots_x;
        Dots[] _dots_y;

        DotValues[] _value_x;
        DotValues[] _value_y;


        float VelocityX;//vận tốc X
        float VelocityY;//vận tốc Y
        float HeightMax;//độ cao max
        float Distance;//khoảng cách
        float Timet;//thời gian


        float _time = 0;

        bool _is_playing = false;
        bool _is_ide = true;

        Camera2d cam = new Camera2d();
        Camera2d cam_x = new Camera2d();
        Camera2d cam_y = new Camera2d();

        Texture2D _background;

        CVectorForce v, vx, vy;

        //CVectorForce _v0_vect;

        public LaunchPhysicsPage()
        {
            InitializeComponent();

            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.Pinch | GestureType.DoubleTap | GestureType.DragComplete;

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        bool fist_load = true;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            if (fist_load)
            {
                // Create a new SpriteBatch, which can be used to draw textures.
                spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
                // TODO: use this.content to load your game content here
                _background = contentManager.Load<Texture2D>("Images/Launch/background");

                _ball = new CBall(spriteBatch, FIST_POSITION, 1, ThrowObliqueSettings.HeightFirst, 0, 0, 0, 0);
                _ball.Init(contentManager);

                Vector2 fPosition = new Vector2(0, FIST_POSITION.Y);
                _x = new CVectorForce(spriteBatch);
                _x.Init(contentManager);
                _x.Create(fPosition, new Vector2(470, 0), 2, Color.YellowGreen);

                Vector2 ffPosition = new Vector2(FIST_POSITION.X, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height);
                _y = new CVectorForce(spriteBatch);
                _y.Init(contentManager);
                _y.Create(ffPosition, new Vector2(0, 790), 2, Color.YellowGreen);


                _dots_x = new Dots[NUMBER_DOT];
                _dots_y = new Dots[NUMBER_DOT];

                _value_x = new DotValues[NUMBER_DOT];
                _value_y = new DotValues[NUMBER_DOT];
                for (int i = 0; i < NUMBER_DOT; i++)
                {
                    Vector2 dot_position_x = new Vector2(40 + 80 * (i + 1), SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height - 100);
                    _dots_x[i] = new Dots(spriteBatch, dot_position_x, 1);
                    _dots_x[i].Init(contentManager);

                    _value_x[i] = new DotValues(spriteBatch, ((i + 1) * 10).ToString() + " m", dot_position_x, true);
                    _value_x[i].Init(contentManager);


                    Vector2 dot_position_y = new Vector2(40, FIST_POSITION.Y - 80 * (i + 1));
                    _dots_y[i] = new Dots(spriteBatch, dot_position_y, 1);
                    _dots_y[i].Init(contentManager);

                    _value_y[i] = new DotValues(spriteBatch, ((i + 1) * 10).ToString() + " m", dot_position_y, false);
                    _value_y[i].Init(contentManager);
                }

                //_v0_vect = new CVectorForce(spriteBatch);
                //_v0_vect.Init(contentManager);
                //_v0_vect.Create(_ball.BallPositon, Vector2

                //

                _waypoints = new List<WayPoint>();

                v = new CVectorForce(spriteBatch);
                v.Init(contentManager);
                v.Create(new Vector2(90, 35), new Vector2(35, 0), 2, Color.Red);
                //v.VectorForce = new Vector2(35, 0);

                vx = new CVectorForce(spriteBatch);
                vx.Init(contentManager);
                vx.Create(new Vector2(90, 67), new Vector2(35, 0), 2, Color.Blue);
                //vx.VectorForce = new Vector2(35, 0);

                vy = new CVectorForce(spriteBatch);
                vy.Init(contentManager);
                vy.Create(new Vector2(90, 99), new Vector2(35, 0), 2, Color.Green);
                ///vy.VectorForce = new Vector2(35, 0);

                fist_load = false;
            }

            // Start the timer
            timer.Start();
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            base.OnNavigatedFrom(e);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        private int number_time = 0;
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            HandleInput();
            if (ThrowObliqueSettings.check_apply)
            {
                GetButton(ButtonTypes.Play_Pause).IsEnabled = true;
                GetButton(ButtonTypes.Refresh).IsEnabled = false;
                GetButton(ButtonTypes.Save).IsEnabled = true;

                //ApplicationBar.Mode = ApplicationBarMode.Default;


                CalculatorFist();
                ThrowObliqueSettings.check_apply = false;
            }
            else
            {
                if (_is_playing)
                {
                    float x;
                    float y;

                    Vector2 tmp_position_1 = _ball.BallPositon;

                    if (_ball.BallPositon.Y >= FIST_POSITION.Y && _ball.BallPositon.X > FIST_POSITION.X)
                    {
                        _time = Timet;

                        _is_playing = false;

                        _ball.BallPositon = new Vector2(_ball.BallPositon.X, FIST_POSITION.Y);
                        _ball.AllowDrawing = false;

                        x = Distance;
                        y = 0;

                        //Vận tốc theo Y
                        VelocityY = (float)(ThrowObliqueSettings.Velocity * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) - ThrowObliqueSettings.Gravity * _time);
                        //Vận tốc theo X
                        VelocityX = (float)(ThrowObliqueSettings.Velocity * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)));

                        WayPoint waypoint_tmp = new WayPoint(spriteBatch, _ball.BallPositon, 0.8f, 0, Distance, _time, VelocityX, VelocityY);
                        waypoint_tmp.Init(contentManager);
                        waypoint_tmp.Active = true;
                        _waypoints.Add(waypoint_tmp);
                        number_time = 0;

                        GetButton(ButtonTypes.Play_Pause).IsEnabled = false;
                        GetButton(ButtonTypes.Play_Pause).IconUri = new Uri("/Assets/AppBar/appbar.transport.play.rest.png", UriKind.Relative);
                        GetButton(ButtonTypes.Play_Pause).Text = "chạy";

                        GetButton(ButtonTypes.Refresh).IsEnabled = true;
                        ApplicationBar.Mode = ApplicationBarMode.Minimized;

                    }
                    else
                    {
                        _time += (float)e.ElapsedTime.TotalMilliseconds / 1000;
                        //Vận tốc theo Y      
                        //Tọa độ của vật theo thời gian
                        x = (float)(ThrowObliqueSettings.Velocity * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * _time);
                        y = ThrowObliqueSettings.HeightFirst + (float)(ThrowObliqueSettings.Velocity * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * _time - (1 / 2f) * _time * _time * ThrowObliqueSettings.Gravity);
                        //float y = (float)(-ThrowObliqueSettings.Gravity * x * x / (2 * ThrowObliqueSettings.Velocity * ThrowObliqueSettings.Velocity * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle))) + Math.Tan(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * x + ThrowObliqueSettings.HeightFirst);

                        //Vận tốc theo Y
                        VelocityY = (float)(ThrowObliqueSettings.Velocity * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) - ThrowObliqueSettings.Gravity * _time);
                        //Vận tốc theo X
                        VelocityX = (float)(ThrowObliqueSettings.Velocity * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)));

                        //vị trí của vật
                        _ball.BallPositon = new Vector2(FIST_POSITION.X + x * CM_PIXEL / RATE_METER, FIST_POSITION.Y - y * CM_PIXEL / RATE_METER);
                        _ball.Vx = VelocityX;
                        _ball.Vy = VelocityY;

                        number_time++;
                        if (number_time == 10)
                        {
                            WayPoint waypoint_tmp = new WayPoint(spriteBatch, _ball.BallPositon, 0.8f, y, x, _time, VelocityX, VelocityY);
                            waypoint_tmp.Init(contentManager);
                            _waypoints.Add(waypoint_tmp);
                            number_time = 0;
                        }

                    }

                    Vector2 tmp_position_2 = _ball.BallPositon;

                    //cập nhật thông số
                    _vx_detail.Text = VelocityX.ToString() + "(m/s)";
                    _vy_detail.Text = VelocityY.ToString() + "(m/s)";
                    _t_detail.Text = _time + "(s)";
                    _ht_detail.Text = y.ToString() + "(m)";
                    _lt_detail.Text = x.ToString() + "(m)";

                    if (y >= 80)
                    {
                        cam.Pos = new Vector2(cam.Pos.X, FIST_POSITION.Y - y * CM_PIXEL / RATE_METER + SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2 - _dots_y[7].DotPositon.Y);
                        cam_y.Pos = new Vector2(cam_y.Pos.X, FIST_POSITION.Y - y * CM_PIXEL / RATE_METER + SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2 - _dots_y[7].DotPositon.Y);
                    }
                    if (x >= 50)
                    {
                        cam.Pos = new Vector2(FIST_POSITION.X + x * CM_PIXEL / RATE_METER + SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2 - _dots_x[4].DotPositon.X, cam.Pos.Y);
                        cam_x.Pos = new Vector2(FIST_POSITION.X + x * CM_PIXEL / RATE_METER + SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2 - _dots_x[4].DotPositon.X, cam_x.Pos.Y);
                    }
                }
                if (!ThrowObliqueSettings.save_active)
                {
                    GetButton(ButtonTypes.Save).IsEnabled = false;
                    ThrowObliqueSettings.save_active = true;
                }
            }
            foreach (WayPoint waypoint in _waypoints)
            {
                waypoint.CamPositon = cam.Pos;
                if (cam.Zoom != 1)
                {
                    if (waypoint.Active)
                    {
                        waypoint.Active = false;
                    }
                    if(!waypoint.AllowDrawing)
                    {
                        waypoint.AllowDrawing = true;
                    }
                }
                waypoint.Update(e);
            }
            _ball.CamPositon = cam.Pos;
            _ball.Update(e);
        }

        private void CalculatorFist()
        {
            _time = 0;
            HeightMax = ThrowObliqueSettings.HeightFirst + (float)((ThrowObliqueSettings.Velocity) * (ThrowObliqueSettings.Velocity) * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) / (2 * ThrowObliqueSettings.Gravity));// chiều cao đi được
            Distance = (float)(2 * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * (ThrowObliqueSettings.Velocity) * (ThrowObliqueSettings.Velocity) / (ThrowObliqueSettings.Gravity)) + (float)(ThrowObliqueSettings.Velocity * Math.Sqrt(2 * ThrowObliqueSettings.HeightFirst * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) / ThrowObliqueSettings.Gravity));//quãng đường đi được             

            //Distance = (float)(2 * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) * (ThrowObliqueSettings.Velocity) * (ThrowObliqueSettings.Velocity) / (ThrowObliqueSettings.Gravity));
            Timet = 2 * ThrowObliqueSettings.Velocity * (float)Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)) / ThrowObliqueSettings.Gravity + (float)Math.Sqrt(2 * ThrowObliqueSettings.HeightFirst / ThrowObliqueSettings.Gravity);//thời gian


            //Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle))
            // t1=v0sinα+2gh+(v0sinα)2g

            Vector2 position_tmp = new Vector2(FIST_POSITION.X, FIST_POSITION.Y - ThrowObliqueSettings.HeightFirst * CM_PIXEL / RATE_METER);
            _ball.BallPositon = position_tmp;
            _ball.AllowDrawing = true;
            _is_ide = true;

            cam.Zoom = 1.0f;
            cam.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width/2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height/2);
            cam_x.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2);
            cam_y.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2);

            float v0_x = (float)(ThrowObliqueSettings.Velocity * Math.Cos(MathHelper.ToRadians(ThrowObliqueSettings.Angle)));
            float v0_y = (float)(ThrowObliqueSettings.Velocity * Math.Sin(MathHelper.ToRadians(ThrowObliqueSettings.Angle)));
            _ball.Vx = v0_x;
            _ball.Vy = v0_y;

            _waypoints.Clear();
            WayPoint waypoint_tmp = new WayPoint(spriteBatch, _ball.BallPositon, 0.8f, ThrowObliqueSettings.HeightFirst,0,0,_ball.Vx, _ball.Vy);
            waypoint_tmp.Init(contentManager);
            _waypoints.Add(waypoint_tmp);


            _vo_detail.Text = ThrowObliqueSettings.Velocity.ToString() + "(m/s)";
            _alpha_detail.Text = ThrowObliqueSettings.Angle.ToString() + "°";
            _g_detail.Text = ThrowObliqueSettings.Gravity.ToString() + "(m/s²)";
            _h_detail.Text = ThrowObliqueSettings.HeightFirst.ToString() + "(m)";

            _hmax_detail.Text = HeightMax.ToString() + "(m)";
            _lmax_detail.Text = Distance.ToString() + "(m)";
            _tmax_detail.Text = Timet.ToString() + "(s)";

            _vx_detail.Text = "0" + "(m/s)";
            _vy_detail.Text = "0" + "(m/s)";
            _t_detail.Text = "0" + "(s)";
            _ht_detail.Text = "0" + "(m)";
            _lt_detail.Text = "0" + "(m)";
        }
        private void HandleInput()
        {
            if (!_is_playing)
            {
                while (TouchPanel.IsGestureAvailable)
                {

                    GestureSample gestureSample = TouchPanel.ReadGesture();

                    switch (gestureSample.GestureType)
                    {
                        case GestureType.Tap:
                            if (cam.Zoom == 1)
                            {
                                foreach (WayPoint waypoint in _waypoints)
                                {
                                    if (waypoint.HandleInput(gestureSample.Position + (cam.Pos - new Vector2(240, 400))))
                                    {
                                        if (waypoint.Active)
                                        {
                                            foreach (WayPoint waypoint_1 in _waypoints)
                                            {
                                                waypoint_1.AllowDrawing = true;
                                            }
                                            waypoint.Active = false;
                                            _vx_detail.Text = "--" + "(m/s)";
                                            _vy_detail.Text = "--" + "(m/s)";
                                            _t_detail.Text = "--" + "(s)";
                                            _ht_detail.Text = "--" + "(m)";
                                            _lt_detail.Text = "--" + "(m)";
                                            break;
                                        }
                                        else
                                        {
                                            foreach (WayPoint waypoint_1 in _waypoints)
                                            {
                                                waypoint_1.AllowDrawing = false;
                                                if (waypoint_1.Active)
                                                {
                                                    waypoint_1.Active = false;
                                                }
                                            }
                                            waypoint.Active = true;
                                            waypoint.AllowDrawing = true;
                                            _vx_detail.Text = waypoint.Vx.ToString() + "(m/s)";
                                            _vy_detail.Text = waypoint.Vy.ToString() + "(m/s)";
                                            _t_detail.Text = waypoint.T.ToString() + "(s)";
                                            _ht_detail.Text = waypoint.H.ToString() + "(m)";
                                            _lt_detail.Text = waypoint.L.ToString() + "(m)";
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        case GestureType.FreeDrag:
                            if (!_is_playing && _is_ide)
                            {

                                if (gestureSample.Position.Y >= _ball.BallPositon.Y - 2 * _ball.BallTexture.Height
                            && gestureSample.Position.Y <= _ball.BallPositon.Y + 2 * _ball.BallTexture.Height
                            && gestureSample.Position.X >= _ball.BallPositon.X - 2 * _ball.BallTexture.Width
                            && gestureSample.Position.X <= _ball.BallPositon.X + 2 * _ball.BallTexture.Width)
                                {
                                    _ball.BallPositon = new Vector2(_ball.BallPositon.X, _ball.BallPositon.Y + gestureSample.Delta.Y);

                                    ThrowObliqueSettings.HeightFirst = (SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height - _ball.BallPositon.Y - 100) * RATE_METER / CM_PIXEL;
                                    if (ThrowObliqueSettings.HeightFirst > 50)
                                        ThrowObliqueSettings.HeightFirst = 50;
                                    else if (ThrowObliqueSettings.HeightFirst < 0)
                                        ThrowObliqueSettings.HeightFirst = 0;

                                    CalculatorFist();
                                }
                                else
                                {
                                    _ball.Vx += gestureSample.Delta.Y * RATE_METER / CM_PIXEL;
                                    _ball.Vy += gestureSample.Delta.X * RATE_METER / CM_PIXEL;

                                    ThrowObliqueSettings.Velocity -= gestureSample.Delta.Y * RATE_METER / CM_PIXEL; //(float)(Math.Sqrt(_ball.Vx * _ball.Vx + _ball.Vy * _ball.Vy));
                                    if (ThrowObliqueSettings.Velocity < 5)
                                    {
                                        ThrowObliqueSettings.Velocity = 5;
                                    }
                                    if (ThrowObliqueSettings.Velocity > 50)
                                    {
                                        ThrowObliqueSettings.Velocity = 50;
                                    }
                                    ThrowObliqueSettings.Angle -= gestureSample.Delta.X * RATE_METER / CM_PIXEL; //(float)Math.Acos(_ball.Vx / ThrowObliqueSettings.Velocity);
                                    if (ThrowObliqueSettings.Angle < 0)
                                    {
                                        ThrowObliqueSettings.Angle = 0;
                                    }
                                    else if (ThrowObliqueSettings.Angle > 90)
                                    {
                                        ThrowObliqueSettings.Angle = 90;
                                    }
                                    CalculatorFist();
                                }
                            }
                            else if (!_is_playing && !_is_ide)
                            {
                                cam.Pos -= gestureSample.Delta;
                                cam_x.Pos -= new Vector2(gestureSample.Delta.X, 0);
                                cam_y.Pos -= new Vector2(0, gestureSample.Delta.Y);
                            }
                            break;
                        case GestureType.DragComplete:
                            if (!_is_playing && _is_ide)
                            {
                                GetButton(ButtonTypes.Save).IsEnabled = true;
                            }
                            break;
                        case GestureType.Pinch:
                            if (!_is_playing && !_is_ide)
                            {
                                Vector2 oldPosition1 = gestureSample.Position - gestureSample.Delta;
                                Vector2 oldPosition2 = gestureSample.Position2 - gestureSample.Delta2;
                                float newDistance = Vector2.Distance(gestureSample.Position, gestureSample.Position2);
                                float oldDistance = Vector2.Distance(oldPosition1, oldPosition2);
                                float scaleFactor = newDistance / oldDistance;
                                cam.Zoom *= scaleFactor;
                            }
                            break;
                        case GestureType.DoubleTap:
                            if (!_is_playing && !_is_ide)
                            {
                                cam.Zoom = 1.0f;
                                cam.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2);
                                cam_x.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2);
                                cam_y.Pos = new Vector2(SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2);
                            }
                            break;
                    }
                }
            }
        }

        //private void HandleInput()
        //{
        //    while (TouchPanel.IsGestureAvailable)
        //    {

        //        GestureSample gestureSample = TouchPanel.ReadGesture();

        //        switch (gestureSample.GestureType)
        //        {
        //            case GestureType.FreeDrag:
        //                Vector2 tmp_vect = gestureSample.Delta;
        //                tmp_vect.Y = -tmp_vect.Y;

        //                if (_v0_vect.VectorForce.X >= 0 && _v0_vect.VectorForce.Y >= 0)
        //                {
        //                    _v0_vect.VectorForce += tmp_vect;
        //                    _v0_vect.VectorForce = new Vector2(_v0_vect.VectorForce.X, _v0_vect.VectorForce.Y);
        //                }

        //                double tanC = _v0_vect.VectorForce.Y / _v0_vect.VectorForce.X;
        //                ThrowObliqueSettings.Angle = (float)MathHelper.ToDegrees((float)Math.Atan(tanC));
        //                if (ThrowObliqueSettings.Angle < 0)
        //                {
        //                    if (_v0_vect.VectorForce.X < 0)
        //                    {
        //                        ThrowObliqueSettings.Angle = 90;
        //                        _v0_vect.VectorForce = new Vector2(0, -_v0_vect.VectorForce.Y);
        //                    }
        //                    else if (_v0_vect.VectorForce.Y < 0)
        //                    {
        //                        ThrowObliqueSettings.Angle = 0;
        //                        _v0_vect.VectorForce = new Vector2(_v0_vect.VectorForce.X, 0);
        //                    }
        //                }
        //                else
        //                {
        //                    if (_v0_vect.VectorForce.X < 0)
        //                    {
        //                        ThrowObliqueSettings.Angle = 90;
        //                        _v0_vect.VectorForce = new Vector2(0, -_v0_vect.VectorForce.Y);
        //                    }
        //                    else if (_v0_vect.VectorForce.Y < 0)
        //                    {
        //                        ThrowObliqueSettings.Angle = 0;
        //                        _v0_vect.VectorForce = new Vector2(_v0_vect.VectorForce.X, 0);
        //                    }
        //                }
        //                _alpha_detail.Text = ThrowObliqueSettings.Angle.ToString();
        //                break;
        //        }
        //    }
        //}

        private void OnDraw(object sender, GameTimerEventArgs e)
        {

            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.White);
            elementRenderer.Render();
            spriteBatch.Begin();
            spriteBatch.Draw(_background, Vector2.Zero, Color.White);
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();

            v.Draw(e);
            vx.Draw(e);
            vy.Draw(e);

            if (cam.Zoom == 1)
            {
                spriteBatch.Begin(SpriteSortMode.BackToFront,
                            BlendState.AlphaBlend,
                            null,
                            null,
                            null,
                            null,
                            cam_x.get_transformation(SharedGraphicsDeviceManager.Current.GraphicsDevice));
                _x.Draw(e);
                for (int i = 0; i < NUMBER_DOT; i++)
                {
                    _dots_x[i].Draw(e);
                    _value_x[i].Draw(e);
                }
                spriteBatch.End();

                spriteBatch.Begin(SpriteSortMode.BackToFront,
                            BlendState.AlphaBlend,
                            null,
                            null,
                            null,
                            null,
                            cam_y.get_transformation(SharedGraphicsDeviceManager.Current.GraphicsDevice));
                _y.Draw(e);
                for (int i = 0; i < NUMBER_DOT; i++)
                {
                    _dots_y[i].Draw(e);
                    _value_y[i].Draw(e);
                }
                spriteBatch.End();
            }

            spriteBatch.Begin(SpriteSortMode.BackToFront,
                        BlendState.AlphaBlend,
                        null,
                        null,
                        null,
                        null,
                        cam.get_transformation(SharedGraphicsDeviceManager.Current.GraphicsDevice));

            foreach (WayPoint waypoint in _waypoints)
            {
                waypoint.Draw(e);
            }
            _ball.Draw(e);
            spriteBatch.End();
        }

        private void RefreshClick(object sender, System.EventArgs e)
        {
            CalculatorFist();

            GetButton(ButtonTypes.Play_Pause).IsEnabled = true;
            GetButton(ButtonTypes.Refresh).IsEnabled = false;

            ApplicationBar.Mode = ApplicationBarMode.Default;
            _is_playing = false;
        }

        public enum ButtonTypes
        {
            Save = 0,
            Play_Pause = 1,
            Refresh = 2
        }
        public ApplicationBarIconButton GetButton(ButtonTypes whichButton)
        {
            return ApplicationBar.Buttons[(int)whichButton]
               as ApplicationBarIconButton;
        }

        private void PlayPauseClick(object sender, System.EventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (!_is_playing)
            {
                GetButton(ButtonTypes.Play_Pause).IconUri = new Uri("/Assets/AppBar/appbar.transport.pause.rest.png", UriKind.Relative);
                GetButton(ButtonTypes.Play_Pause).Text = "dừng";

                GetButton(ButtonTypes.Refresh).IsEnabled = false;
                _is_playing = true;
                _is_ide = false;
            }
            else
            {
                GetButton(ButtonTypes.Play_Pause).IconUri = new Uri("/Assets/AppBar/appbar.transport.play.rest.png", UriKind.Relative);
                GetButton(ButtonTypes.Play_Pause).Text = "chạy";

                GetButton(ButtonTypes.Refresh).IsEnabled = true;
                _is_playing = false;
            }
        }
        private void InfoClick(object sender, System.EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ThrowOblique/InfoThrowObliquePage.xaml", UriKind.Relative));
        	// TODO: Add event handler implementation here.
        }


        private void SaveClick(object sender, System.EventArgs e)
        {
            if (!Guide.IsVisible)
            {
                // display the guide

                Guide.BeginShowKeyboardInput(PlayerIndex.One,
                    "Tên",       // title for the page
                    "Nhập tên mô phỏng",  // question for user
                    null,             // default text
                    new AsyncCallback(GotTextName),  // callback method 
                    this);                       // object reference
            }

        	
        }
        void GotTextName(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                List<ThrowObliqueData> datas = ThrowObliqueData.Load();
                
                string text = Guide.EndShowKeyboardInput(result);

                if (text != null)
                {
                    if (text == "")
                    {
                        text = "unknown";
                    }
                    ThrowObliqueSettings.save_active = false;
                    ThrowObliqueData data = new ThrowObliqueData(text, ThrowObliqueSettings.Angle, ThrowObliqueSettings.Velocity, ThrowObliqueSettings.Gravity, ThrowObliqueSettings.HeightFirst);
                    datas.Add(data);
                    ThrowObliqueData.SaveData(datas);
                }
            }
        }

        private void LoadSimalatorClick(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            NavigationService.Navigate(new Uri("/ThrowOblique/SaveThrowObliquePage.xaml", UriKind.Relative));
        }

        private void NhapThongSo_Click(object sender, System.EventArgs e)
        {
            _is_playing = false;
            NavigationService.Navigate(new Uri("/ThrowOblique/EditThrowObliquePage.xaml", UriKind.Relative));
        }

    }
}